<?php

namespace app\admin\model;

use think\Model;


class CardOrder extends Model
{

    

    

    // 表名
    protected $name = 'card_order';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'pay_time_text'
    ];
    

    



    public function getPayTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['pay_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPayTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function calculate($discount)
    {
        $card = \app\admin\model\Card::get(1);

        if ($discount){
            $real_discount = $card->discount/10;
        } else {
            $real_discount = 1;
        }

        $data = [
            'month_price'=>bcmul($card->month_price,$real_discount,2),
            'quarter_price'=>bcmul($card->quarter_price,$real_discount,2),
            'year_price'=>bcmul($card->year_price,$real_discount,2),
        ];

        return $data;
    }

    public function add($param)
    {
        //$card = \app\admin\model\Card::get($param['card_id']);

        $type = $param['type'];//1月,2季,3年
        $discount = $param['discount'];
        $calculate = $this->calculate($discount);
        if ($type==1){
            $price = $calculate['month_price'];
        } elseif ($type==2){
            $price = $calculate['quarter_price'];
        } else {
            $price = $calculate['year_price'];
        }
        $model = new CardOrder();

        $data = [
            'user_id'        => $param['user_id'],
            'price'          => $price,
            'order_no'       => $this->order_no(),
            'type'           => $type,
        ];

        $wechatUser = User::get($param['user_id']);
        $model->data($data);
        $res =  $model->save();

        if ($res){
            $request = request();
            $notifyurl =  $request->root(true)."/api/block/cardnotifyx";

            $pay = \addons\epay\library\Service::submitOrder($data['price'],$data['order_no'],'wechat','会员卡',$notifyurl,'','miniapp',$wechatUser['wechat_open_id']);
            return $pay;
        } else {
            return false;
        }
    }

    public function order_no(){
        $order_no = null;
        while (true) {
            $order_no = date('YmdHis') . mt_rand(1000, 9999);
            $exist_order_no = CardOrder::get(['order_no' => $order_no]);
            if (!$exist_order_no) {
                break;
            }
        }
        return $order_no;
    }
}
